package com.tarena.luban.worker.server.domain.service;

import com.tarena.luban.worker.server.domain.bo.*;
import com.tarena.luban.worker.server.domain.repository.WorkerAreaRepository;
import com.tarena.luban.worker.server.domain.repository.WorkerCategoryRepository;
import com.tarena.luban.worker.server.domain.repository.WorkerRepository;
import com.tarena.passport.protocol.LoginUser;
import com.tarena.passport.sdk.context.SecurityContext;
import com.tarena.tp.attach.server.client.AttachApi;
import com.tarena.tp.attach.server.dto.AttachDTO;
import com.tarena.tp.attach.server.param.AttachUpdateParam;
import com.tarena.tp.attach.server.query.AttachQuery;
import com.tarena.tp.luban.account.server.client.AccountApi;
import com.tarena.tp.luban.account.server.dto.AccountDTO;
import com.tarena.tp.luban.worker.server.common.enums.ResultEnum;
import com.tarena.tp.luban.worker.server.dto.param.IdCardParam;
import com.tarena.tp.luban.worker.server.dto.param.WorkerCreateParam;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class WorkerService {
    // 当前师傅业务层注入4个仓储层 分别对应四个表格 workerRepo workerAreaRepo workerCateRepo
    // workerAuditRepo
    public Long create(WorkerCreateParam workerCreateParam) throws BusinessException {
        // 1. 新增师傅,每个师傅要绑定一个userId,来自于认证解析
        Long userId = getUserId();
        workerCreateParam.setUserId(userId);
        //2. 连接第三方的接口资源 验证真名和身份师傅匹配
        checkIdCard(workerCreateParam);
        //3.将数据 写入到三个不同的数据表格 Worker worker_area worker_category
        //3.1 新增师傅数据
        Long workerId = saveWorker(workerCreateParam);
        //3.2 新增区域数据 worker_area 和area表格歪哥关键表
        saveWorkerArea(workerCreateParam);
        //3.3 新增品类数据worker_category
        saveWorkerCategory(workerCreateParam);
        //返回workerId
        return workerId;
    }

    @Autowired
    private WorkerRepository workerRepository;
    //考虑 幂等 (不做幂等如果第一次入驻被驳回的话第二次申请就不会覆盖原有的数据库数据,不符)
    //1. 先删除 后新增
    //2. 先userId查询是否存在,如果已经存在,直接更新update 不存在则insert
    @Autowired(required = false)
    private AttachApi attachApi;

    private Long saveWorker(WorkerCreateParam workerCreateParam) throws BusinessException {
        // 先删除,一个登录的用户只能绑定 入驻申请一个师傅
        workerRepository.delete(workerCreateParam.getUserId());
        // 新增
        Long workerId = workerRepository.saveWorker(workerCreateParam);
        //使用当前数据参数 远程调用
        List<AttachUpdateParam> updateAttaches = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(workerCreateParam.getAttachList())) {
            // 有图片需要绑定
            List<IdCardParam> attachList = workerCreateParam.getAttachList();
            for (IdCardParam idCardParam : attachList) {
                AttachUpdateParam attachUpdateParam = new AttachUpdateParam();
                attachUpdateParam.setId(idCardParam.getId());
                attachUpdateParam.setBusinessId(workerId.intValue());
                attachUpdateParam.setBusinessType(100);//师傅业务类型就是100 还有订单施工图片200
                attachUpdateParam.setIsCover(1);
                updateAttaches.add(attachUpdateParam);
            }
            attachApi.batchUpdateAttachByIdList(updateAttaches);
        } else {
            //
            throw new BusinessException(ResultEnum.ATTACH_FAILED);
        }
        return workerId;
    }

    @Autowired
    private WorkerCategoryRepository workerCategoryRepository;

    private void saveWorkerCategory(WorkerCreateParam workerCreateParam) {
        //删除
        workerCategoryRepository.delete(workerCreateParam.getUserId());
        //新增批量品类
        workerCategoryRepository.saveWorkerCategory(workerCreateParam);
    }

    @Autowired
    private WorkerAreaRepository workerAreaRepository;
    //考虑 幂等
    private void saveWorkerArea(WorkerCreateParam workerCreateParam) {
        //删除
        workerAreaRepository.delete(workerCreateParam.getUserId());
        //新增区域
        workerAreaRepository.saveWorkerArea(workerCreateParam);
    }


    private void checkIdCard(WorkerCreateParam workerCreateParam) {
        //UNDO 调用阿里 百度 腾讯 接口 传递真名和身份证号
    }

    private Long getUserId() throws BusinessException {
        LoginUser user = SecurityContext.getLoginToken();
        //如果jwt没有携带数据,或者解析有问题 user有可能是空
        if (user == null) {
            throw new BusinessException(ResultEnum.USER_TOKEN_VERIFY_FAILED);
        }
        return user.getUserId();
    }

    @Autowired
    private AccountApi accountApi;

    public WorkerBO detailWorker() throws BusinessException {
        WorkerBO workerBO = null;
        //1. 一批来自worker数据id userId phone realName
        Long userId = getUserId();
        // 查询worker
        workerBO = workerRepository.detail(userId);
        if (workerBO == null || workerBO.getId()==null) {
            //当前userId 没有入驻师傅 手动封装一个结果 所有属性都是空 只有2个 accountBO auditStatus=3
            workerBO = new WorkerBO();
            workerBO.setAuditStatus(3); //3=未入驻
            AccountBO accountBO = new AccountBO();
            accountBO.setTotalAmount(0L);
            workerBO.setAccountBO(new AccountBO());
            return workerBO;
        }
        //2. 一批绑定区域 list
        List<WorkerAreaBO> areaBOS = workerAreaRepository.getAreas(userId);
        workerBO.setWorkerAreaBOList(areaBOS);
        //3. 一批绑定品类 list
        List<WorkerCategoryBO> categoryBOS = workerCategoryRepository.getCategories(userId);
        workerBO.setWorkerCategoryBOList(categoryBOS);
        //4. 2张绑定图片url地址 businessType=100 businessId=workerId
        List<AttachInfoBO> attachBOS = new ArrayList<>();
        AttachQuery attachQuery = new AttachQuery();
        attachQuery.setBusinessId(workerBO.getId().intValue());
        attachQuery.setBusinessType(100);
        List<AttachDTO> attachDTOS= attachApi.getAttachInfoByParam(attachQuery);
        //AttachDTO 包括图片新名称 旧名称 大小 长 宽等参数,基本对应attach表格字段
        //AttachInfoBO 只需要封装url 图片访问地址. http://localhost:8092/static/+ fileUuid
        //做封装
        if(CollectionUtils.isNotEmpty(attachDTOS)) {
            //绑定图片不为空 才封装
            for (AttachDTO attachDTO : attachDTOS) {
                //使用图片dto对象 fileUuid 拼接url
                String url = "http://localhost:8092/static/" + attachDTO.getFileUuid();
                AttachInfoBO attachInfoBO = new AttachInfoBO();
                attachInfoBO.setUrl(url);
                attachBOS.add(attachInfoBO);
            }
        }
        workerBO.setAttachInfoBOList(attachBOS);
        //5. 当前登录的用户绑定的账号
        AccountDTO accountDTO = accountApi.getAccountByUserId(userId);
        //不一定可以查到,师傅刚注入还没有审核通过时,查不到
        AccountBO accountBO = new AccountBO();
        accountBO.setTotalAmount(0L);
        if (accountDTO == null||accountDTO.getUserId()==null) {
            //当前user绑定了账户
            accountBO.setTotalAmount(accountDTO.getTotalAmount());
        }
        workerBO.setAccountBO(accountBO);
        return workerBO;
    }
}
